package com.example.springaiollamademo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.example.springaiollamademo.dto.ChatResponse;
import com.example.springaiollamademo.dto.ChatWithSystemRequest;
import com.example.springaiollamademo.service.ChatService;

/**
 * @author 张飞
 * @version 1.0
 * @since 2025-07-14
 */
@RestController
@RequestMapping("/api/ollama")
@CrossOrigin(origins = "*")
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private ChatService chatService;

    /**
     * 带系统提示的聊天（Markdown格式回答）
     */
    @PostMapping("/chat-with-system")
    public ChatResponse chatWithSystem(@RequestBody ChatWithSystemRequest request) {
        logger.info("=== POST /api/ollama/chat-with-system 请求开始 ===");
        logger.info("接收到POST请求体: {}", request != null ? "ChatWithSystemRequest对象" : "null");
        
        if (request != null) {
            logger.info("请求参数: prompt=[{}], systemMessage=[{}]", 
                request.getPrompt(), request.getSystemMessage());
        }
        
        try {
            logger.info("开始调用ChatService.chatWithSystem()方法");
            String response = chatService.chatWithSystem(request.getPrompt(), request.getSystemMessage());
            logger.info("ChatService.chatWithSystem()方法执行成功，响应长度: {} 字符", response != null ? response.length() : 0);
            
            ChatResponse chatResponse = new ChatResponse(true, response, null);
            logger.info("POST /chat-with-system 请求处理成功，返回成功响应");
            return chatResponse;
        } catch (Exception e) {
            logger.error("POST /api/ollama/chat-with-system 请求处理失败", e);
            ChatResponse errorResponse = new ChatResponse(false, null, "处理请求时发生错误: " + e.getMessage());
            logger.info("返回错误响应: {}", errorResponse.getError());
            return errorResponse;
        } finally {
            logger.info("=== POST /api/ollama/chat-with-system 请求结束 ===");
        }
    }

    /**
     * 带系统提示的流式聊天（Markdown格式回答）
     * 优化：AI响应慢时先发送"思考中"提示，AI数据到来后停止
     */
    @PostMapping(value = "/chat-with-system-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatWithSystemStream(@RequestBody ChatWithSystemRequest request) {
        logger.info("=== POST /api/ollama/chat-with-system-stream 流式请求开始 ===");
        logger.info("接收到流式请求参数: prompt=[{}], systemMessage=[{}]", 
            request != null ? request.getPrompt() : "null",
            request != null ? request.getSystemMessage() : "null");
        
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时
        
        try {
            // 立即发送初始"思考中"提示，避免前端等待超时
            logger.info("发送初始思考提示");
            emitter.send(SseEmitter.event()
                .name("thinking")
                .data("data: <think>AI正在思考中，请稍候...</think>\n\n"));
            
            logger.info("开始调用ChatService.chatWithSystemStream()方法");
            chatService.chatWithSystemStream(request.getPrompt(), request.getSystemMessage(), emitter);
            logger.info("带系统提示的流式请求处理启动成功");
        } catch (Exception e) {
            logger.error("POST /api/ollama/chat-with-system-stream 请求处理失败", e);
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("处理请求时发生错误: " + e.getMessage()));
                emitter.complete();
            } catch (Exception sendException) {
                logger.error("发送错误信息失败", sendException);
                emitter.completeWithError(sendException);
            }
        }
        
        return emitter;
    }
}
